<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/mes/mes/StockIn.jsx或StockIn.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="grid">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields" :searchFormOptions="searchFormOptions"
            :table="table" :extend="extend" :onInit="onInit" :onInited="onInited" :searchBefore="searchBefore"
            :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore" :rowClick="rowClick"
            :delBefore="delBefore" :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>
        </view-grid>
    </div>
    <select-material ref="materialRef" @onSelectMaterial="onSelectMaterial"></select-material>
</template>
<script setup lang="jsx">
import extend from "@/extension/mes/mes/StockIn.jsx";
import viewOptions from './StockIn/options.js'
import SelectMaterial from './StockInSelectMaterial.vue'
import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())

let gridRef;//对应[表.jsx]文件中this.使用方式一样
const materialRef = ref();
//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;

}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    columns.forEach(x => {
        //开启表头过滤
        x.filterData = true;
    })
    
    gridRef.buttons.splice(3, 0, {
        name: '同步到云星辰', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            SyncData();
        }
    })
    gridRef.buttons.splice(3, 0, {
        name: '同步入库成本到云星辰', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            SyncDataCost();
        }
    })
    //选择物料
    const materialNoCol = gridRef.detailOptions.columns.find((x) => {
        return x.field == 'MaterialNo'
    })
    materialNoCol.render = (h, { row, column, index }) => {

        return (
            <div>
                <el-button
                    link
                    onClick={($e) => {
                        materialRef.value.open(row)
                    }}
                    class="el-icon-search"
                    style="color: #2196F3;cursor: pointer;"
                ></el-button>

                <span style="margin-right:5px">{row.MaterialNo}</span>
            </div>
        )

    }

    // 根据单价数量计算金额
    gridRef.detailOptions.columns.forEach((col) => {
        //给数量Qty字段合计自定义显示格式、同时与表单联动显示
        if (col.field == 'Amount') {
            //将eidt设置为null不开启编辑
            col.edit = null;
            col.formatter = (row) => {
                row.Amount = row.Qty * row.Price
                return row.Qty * row.Price
            }
        }
    });

    gridRef.detailOptions.columns.forEach(c => {
        if (c.field == 'LotText') {
            c.checkEdit = (row, column, index) => {
                if (row.IsLoted == 1) {
                    c.required = true
                    return true
                }
                else {
                    c.required = false
                    return false
                }
            }
        }

    })

    gridRef.detailOptions.columns.forEach(x => {
        if (x.field == 'MaterialId') {
            //将eidt设置为null不开启编辑
            x.edit = null;
            initLotSelectTable()
        }
    })
    gridRef.detailOptions.columns.forEach(x => {
        if (x.field == 'StockId') {
            //如果字段是下拉框或日期，添加onChange事件
            x.onChange = (row, column, event) => {
                selectChange(row, column)
            }
        }
    })
}
//触发第二个下拉框联动操作
const selectChange = (row, column) => {
    //找到第二个下拉框选项
    let col = gridRef.detailOptions.columns.find((c) => { return c.field == 'LocationId' })
    let url = 'api/Location/getLocationByStockId'
    //从后台返回第二个下拉框满足条件的数据
    proxy.http.post(url, row.StockId, false).then((locationInfos) => {
        //keys只返回第二个下拉框的key值，用于下面的判断，返回的下拉框key选项显示，没有返回的隐藏
        console.log(locationInfos)
        col.bind.data.forEach((item) => {
            console.log(item)
            console.log(item.key)
            console.log(locationInfos[0] == item.key)

            //注意：第二个下拉框选项，在下拉框绑定页面，配置的字典sql需要将全部数据源返回
            //如果返回的数据源有几十W，请考虑用弹出框选择数据，不要用下拉框
            if (locationInfos.indexOf(item.key + '') != -1) {
                console.log(item.key)
                item.hidden = false
            } else {
                console.log(item.key)
                item.hidden = true
            }
        })
    })
}
const initLotSelectTable = () => {

    gridRef.detailOptions.columns.forEach((item) => {
        if (item.field == 'LotText') {
            item.edit = { type: "selectTable" }
            item.readonly = false;

            item.url = 'api/LotMasterDetail/search';

            //输入框只读操作，需要将columns的search字段设置为true，否则无法过滤数据
            //item.inputReadonly=true;
            //设置显示的字段
            item.columns = [
                { field: 'LotMasterDetailId', title: '批号明细标识', type: 'string', width: 120, hidden: true },
                { field: 'LotText', title: '批号', type: 'string', width: 100, search: true },
            ];

            //选中table数据后，回写到表单
            //editRow:当前正在编辑的行
            //rows:选中的行
            item.onSelect = (editRow, rows) => {
                editRow.LotMasterDetailId = rows[0].LotMasterDetailId;
                editRow.LotText = rows[0].LotText;
            };

            //(输入框搜索)表格数据加载前处理
            //editRow:当前正在编辑的行
            //param:请求的参数
            item.loadBefore = (editRow, param, callback) => {

                param.value = editRow.MaterialId;
                callback(true);
            };

            //表格数据加载后处理
            //editRow:当前正在编辑的行
            //rows:后台返回的数据
            item.loadAfter = (editRow, rows, callback, result) => {
                callback(true);
            };

            /****下面的这些都是可以选配置，上面的是必填的******/
            //监听输入框变动与回车事件
            item.onKeyPress = (val, $event, row) => {
                console.log(val);
                if ($event.keyCode == 13) {
                    console.log('按了回车');
                }
                //清空值时给其他字段设置值
                // if(!val&&value+''!='0'){
                //     row.xx=null;
                // }
            }
            //设置弹出框高度(默认200)
            item.height = 200;
            //设置弹出框宽度(默认500)
            item.selectWidth = 500;
            item.textInline = true; //设置表格超出显示...
            //设置表格是否单选
            item.single = true;
            //隐藏分页
            item.paginationHide = true;
            //设置默认分页大小与分页信息
            item.pagination = { size: 30, sizes: [30, 60, 90] };
        }
    });
}

const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询
    return true;
}
const searchAfter = async (rows, result) => {
    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
} 
const delBefore = (ids, rows) => { //查询界面的表删除前 ids为删除的id数组,rows删除的行
    let isDeleted = true
    rows.forEach(row => {
        if (row.AuditStatus != 0 && row.AuditStatus != null) {
            isDeleted = false
            proxy.$message.error(row.BillNo + "已审核不允许删除！");
            return isDeleted;
        }
    });
    return isDeleted;//返回false，界面上不会显示
}
const rowClick = ({ row, column, event }) => {
    grid.value.clearSelection();
    //查询界面点击行事件
    grid.value.toggleRowSelection(row); //单击行时选中当前行;
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
    gridRef.editFormFields.BillDate = proxy.base.getDate()

}


const SyncData = () => {
    var rows = gridRef.getSelectRows()
    if (rows.length == 0) {
        proxy.$message.error("请选择入库单");
        return
    }
    if (rows[0].AuditStatus != 1) {
        proxy.$message.error("入库单未审核");
        return
    }
    let url = 'api/StockIn/syncData';
    proxy.http.post(url, rows).then((result) => {

        proxy.$message.success("同步数据成功！");
    });
}
const SyncDataCost = () => {
    var rows = gridRef.getSelectRows()
    if (rows.length == 0) {
        proxy.$message.error("请选择入库单");
        return
    }
    if (rows[0].AuditStatus != 1) {
        proxy.$message.error("入库单未审核");
        return
    }
    let url = 'api/StockIn/syncDataCost';
    proxy.http.post(url, rows).then((result) => {

        proxy.$message.success("同步数据成功！");
    });
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
